<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { userLogoutUsingPost } from '@/api/userController.ts'

const loginUser = useLoginUserStore()


interface NavItem {
  id: string | number
  title: string
  path?: string
  children?: NavItem[]
  icon?: string
  meta?: { badge?: number | (() => number); hide?: boolean; newWindow?: boolean }
}

/* ========== 0. 导航数据直接写在组件里，拿来即用 ========== */
const navList = ref<NavItem[]>([
  { id: 1, title: '主页', icon: '🏠', path: '/' },
  { id: 2, title: '上传图片', icon: '➕', path: '/picture/create' },
  { id: 3, title: '批量抓取图片', icon: '📥', path: '/picture/addBatch' },
  { id: 4, title: '图片管理', icon: '🖼️', path: '/picture/manager' },
  { id: 5, title: '待审核图片', icon: '🔍', path: '/review' },
  { id: 6, title: '浏览历史', icon: '🕒', path: '/history' },
  { id: 7, title: '标签管理', icon: '🏷️', path: '/admin/tagManage' },
  { id: 8, title: '分类管理', icon: '📂', path: '/admin/categoryManage' },
  { id: 9, title: '用户管理', icon: '👤', path: '/admin/userManage' },
])
/* ========== 1. props 仅留可外部覆盖的项 ========== */
const props = withDefaults(
  defineProps<{
    logo?: string
    title?: string
    fixed?: boolean
    sticky?: boolean
    theme?: 'light' | 'dark'
    accordion?: boolean
    showSearch?: boolean
    showUser?: boolean
    avatar?: string
    username?: string
    userMenu?: NavItem[]
  }>(),
  {
    logo: 'src/assets/logo.png',
    title: '潮汐智能云图库',
    fixed: true,
    sticky: false,
    theme: 'light',
    accordion: true,
    showSearch: true,
    showUser: true,
    avatar: '',
    username: 'Admin',
    userMenu: () => [
      { id: 1, title: '个人中心', path: '/user/center' },
      { id: 2, title: '作品与收藏', path: '/user/profile' },
      { id: 3, title: '退出登录', path: '/logout' },
    ],
  },
)

/* ========== 2. 事件 & 逻辑（无改动） ========== */
const emit = defineEmits<{
  select: [item: NavItem]
  search: [keyword: string]
  userMenuClick: [item: NavItem]
}>()

const router = useRouter()
const route = useRoute()

const searchVisible = ref(false)
const searchKeyword = ref('')
const showMobileMenu = ref(false)
const showUserDropdown = ref(false)
const openSubMenu = ref<(string | number)[]>([])
const isScrolled = ref(false)

// 根据用户角色过滤导航项
const filteredNavList = computed(() => {
  // 检查用户是否已登录
  const isLoggedIn = loginUser.loginUser.userName !== '未登录';

  // 如果用户未登录，只显示主页
  if (!isLoggedIn) {
    return navList.value.filter(item => item.path === '/');
  }

  // 检查用户是否为管理员
  const isAdmin = loginUser.loginUser.userRole === 'admin';

  // 如果是管理员，过滤掉普通用户专用的页面
  if (isAdmin) {
    return navList.value.filter(item => {
      // 过滤掉普通用户专用页面
      const userPaths = ['/history', '/review'];
      if (userPaths.includes(item.path || '')) {
        return false;
      }
      return true;
    });
  }

  // 如果是普通用户，过滤掉管理员专用的页面
  return navList.value.filter(item => {
    // 过滤掉管理员专用页面（仅管理员可见）
    const adminPaths = ['/picture/addBatch', '/picture/manager', '/admin/userManage', '/admin/categoryManage', '/admin/tagManage'];
    if (adminPaths.includes(item.path || '')) {
      return false;
    }
    return true;
  });
});


const activeRootId = computed(() => {
  const find = (list: NavItem[]): string | number | undefined => {
    for (const item of list) {
      // 精确匹配路径
      if (item.path && route.path === item.path) {
        return item.id
      }
      // 前缀匹配（适用于有子路由的情况）
      if (item.path && item.path !== '/' && route.path.startsWith(item.path)) {
        return item.id
      }
      // 递归检查子项
      if (item.children) {
        const childResult = find(item.children)
        if (childResult) {
          return item.id
        }
      }
    }
    return undefined
  }

  const result = find(filteredNavList.value)
  return result ?? ''
})

watch(
  () => route.path,
  () => {
    // 依赖于 activeRootId 的 computed 属性会自动更新
  }
)


const getBadge = (m?: NavItem['meta']) => {
  if (!m?.badge) return 0
  return typeof m.badge === 'function' ? m.badge() : m.badge
}

const toggleSubMenu = (id: string | number) => {
  openSubMenu.value = props.accordion
    ? [id]
    : openSubMenu.value.includes(id)
      ? openSubMenu.value.filter((k) => k !== id)
      : [...openSubMenu.value, id]
}

const onNavClick = (item: NavItem) => {
  emit('select', item)
  if (item.meta?.newWindow && item.path) {
    window.open(item.path, '_blank')
    return
  }
  if (item.path) {
    router.push(item.path)
    showMobileMenu.value = false
    openSubMenu.value = []
  }
}

// 登出处理函数
const handleLogout = async () => {
  try {
    const res = await userLogoutUsingPost()
    if (res.data.code === 0) {
      // 清除用户状态
      loginUser.setLoginUser({ userName: '未登录' })
      // 跳转到登录页
      router.push('/user/login')
    }
  } catch (error) {
    console.error('登出失败', error)
  }
}

const onSearch = () => {
  emit('search', searchKeyword.value.trim())
  searchVisible.value = false
}

// onUserMenuClick 函数
const onUserMenuClick = (item: NavItem) => {
  emit('userMenuClick', item)
  showUserDropdown.value = false
  // 登出逻辑处理
  if (item.title === '退出登录') {
    handleLogout()
  } else if (item.path && item.path !== '/logout') {
    // 处理其他菜单项的路由跳转
    router.push(item.path)
  }
}

const onClickOutside = (e: Event) => {
  if (!(e.target as HTMLElement).closest('.global-nav')) showUserDropdown.value = false
}

const onScroll = () => (isScrolled.value = window.scrollY > 0)

onMounted(() => {
  document.addEventListener('click', onClickOutside)
  window.addEventListener('scroll', onScroll)
})
onUnmounted(() => {
  document.removeEventListener('click', onClickOutside)
  window.removeEventListener('scroll', onScroll)
})
</script>

<template>
  <header
    class="global-nav"
    :class="[theme, { fixed, sticky: props.sticky, scrolled: isScrolled }]"
  >
    <div class="nav-wrapper">
      <div class="nav-brand" @click="$router.push('/')">
        <img v-if="props.logo" :src="props.logo" class="logo" alt="logo" />
        <span class="title">{{ props.title }}</span>
      </div>

      <!-- 桌面菜单 -->
      <nav class="nav-menu desktop">
        <template v-for="item in filteredNavList" :key="item.id">
          <template v-if="!item.children?.length">
            <a
              v-if="!item.meta?.hide"
              class="nav-item"
              :class="{ active: activeRootId === item.id }"
              @click="onNavClick(item)"
            >
              <i v-if="item.icon" class="nav-icon">{{ item.icon }}</i>
              <span>{{ item.title }}</span>
              <span v-if="getBadge(item.meta)" class="badge">{{ getBadge(item.meta) }}</span>
            </a>
          </template>
          <div v-else class="nav-item has-child">
            <div class="nav-title-wrapper" @click="toggleSubMenu(item.id)">
              <i v-if="item.icon" class="nav-icon">{{ item.icon }}</i>
              <span>{{ item.title }}</span>
              <i class="arrow" :class="{ open: openSubMenu.includes(item.id) }"></i>
              <span v-if="getBadge(item.meta)" class="badge">{{ getBadge(item.meta) }}</span>
            </div>
            <transition name="slide-down">
              <ul v-show="openSubMenu.includes(item.id)" class="sub-menu">
                <li
                  v-for="child in item.children"
                  :key="child.id"
                  class="sub-item"
                  @click="onNavClick(child)"
                >
                  <i v-if="child.icon" class="nav-icon">{{ child.icon }}</i>
                  <span>{{ child.title }}</span>
                  <span v-if="getBadge(child.meta)" class="badge">{{ getBadge(child.meta) }}</span>
                </li>
              </ul>
            </transition>
          </div>
        </template>
      </nav>

      <!-- 右侧工具区 -->
      <div class="nav-tools">
        <div v-if="props.showSearch" class="search-box" :class="{ active: searchVisible }">
          <input
            v-if="searchVisible"
            v-model="searchKeyword"
            v-focus
            type="text"
            placeholder="搜索..."
            @keyup.enter="onSearch"
            @blur="searchVisible = false"
          />
          <i class="icon-search" @click="searchVisible = !searchVisible">🔍</i>
        </div>

        <!-- 用户：未登录显示登录按钮，已登录显示用户信息 -->
        <div v-if="props.showUser" class="user-box">
          <!-- 未登录 -->
          <a-button
            v-if="loginUser.loginUser.userName === '未登录'"
            type="primary"
            size="small"
            @click="$router.push('/user/login')"
          >
            登录
          </a-button>

          <!-- 已登录 -->
          <template v-else>
            <div class="user-trigger" @click="showUserDropdown = !showUserDropdown">
              <img v-if="props.avatar" :src="props.avatar" class="avatar" alt="avatar" />
              <i v-else class="avatar-placeholder">👤</i>
              <span class="username">{{ loginUser.loginUser.userName }}</span>
              <i class="arrow" :class="{ open: showUserDropdown }"></i>
            </div>
            <transition name="slide-down">
              <ul v-show="showUserDropdown" class="user-dropdown">
                <li
                  v-for="item in props.userMenu"
                  :key="item.id"
                  class="user-item"
                  @click="onUserMenuClick(item)"
                >
                  <i v-if="item.icon" class="nav-icon">{{ item.icon }}</i>
                  <span>{{ item.title }}</span>
                </li>
              </ul>
            </transition>
          </template>
        </div>

        <!-- 移动端汉堡 -->
        <div class="mobile-toggle" @click="showMobileMenu = !showMobileMenu">
          <span class="bar"></span><span class="bar"></span><span class="bar"></span>
        </div>
      </div>
    </div>

    <!-- 移动端抽屉 -->
    <transition name="slide-right">
      <div v-if="showMobileMenu" class="mobile-drawer">
        <div class="mobile-header">
          <span class="mobile-title">菜单</span>
          <i class="icon-close" @click="showMobileMenu = false">✕</i>
        </div>
        <nav class="nav-menu mobile">
          <template v-for="item in filteredNavList" :key="item.id">
            <template v-if="!item.children?.length">
              <a
                v-if="!item.meta?.hide"
                class="nav-item"
                :class="{ active: activeRootId === item.id }"
                @click="onNavClick(item)"
              >
                <i v-if="item.icon" class="nav-icon">{{ item.icon }}</i>
                <span>{{ item.title }}</span>
                <span v-if="getBadge(item.meta)" class="badge">{{ getBadge(item.meta) }}</span>
              </a>
            </template>
            <div v-else class="nav-item has-child">
              <div class="nav-title-wrapper" @click="toggleSubMenu(item.id)">
                <i v-if="item.icon" class="nav-icon">{{ item.icon }}</i>
                <span>{{ item.title }}</span>
                <i class="arrow" :class="{ open: openSubMenu.includes(item.id) }"></i>
                <span v-if="getBadge(item.meta)" class="badge">{{ getBadge(item.meta) }}</span>
              </div>
              <transition name="slide-down">
                <ul v-show="openSubMenu.includes(item.id)" class="sub-menu">
                  <li
                    v-for="child in item.children"
                    :key="child.id"
                    class="sub-item"
                    @click="onNavClick(child)"
                  >
                    <i v-if="child.icon" class="nav-icon">{{ child.icon }}</i>
                    <span>{{ child.title }}</span>
                    <span v-if="getBadge(child.meta)" class="badge">{{
                      getBadge(child.meta)
                    }}</span>
                  </li>
                </ul>
              </transition>
            </div>
          </template>
        </nav>
      </div>
    </transition>

    <transition name="fade">
      <div v-if="showMobileMenu" class="drawer-mask" @click="showMobileMenu = false"></div>
    </transition>
  </header>
</template>

<script lang="ts">
export default {
  directives: {
    focus: {
      mounted(el: HTMLElement) {
        el.focus()
      },
    },
  },
}
</script>

<style scoped>
/* 样式与之前完全一致，已压缩节省篇幅 */
.global-nav {
  width: 100%;
  height: 64px;
  line-height: 64px;
  padding: 0 24px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  z-index: 1000;
  transition: box-shadow 0.3s;
}
.global-nav.scrolled {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}
.global-nav.fixed {
  position: fixed;
  top: 0;
  left: 0;
}
.global-nav.sticky {
  position: sticky;
  top: 0;
}
.global-nav.dark {
  background: #001529;
  color: #fff;
}
.nav-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
  max-width: 1440px;
  margin: 0 auto;
}
.nav-brand {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 0;
}
.logo {
  height: 32px;
  margin-right: 12px;
}
.title {
  font-size: 20px;
  font-weight: 600;
  white-space: nowrap;
}
.nav-menu.desktop {
  display: flex;
  align-items: center;
  flex: 1;
  margin: 0 24px;
  overflow-x: auto;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE 10+ */
}
.nav-menu.desktop::-webkit-scrollbar {
  width: 0px;
  height: 0px;
  background: transparent; /* Chrome/Safari/Webkit */
}
.nav-item {
  display: flex;
  align-items: center;
  padding: 0 12px;
  height: 64px;
  cursor: pointer;
  transition: background 0.3s;
  color: #333;
  white-space: nowrap;
  flex-shrink: 0;
}
.nav-item:hover {
  background: rgba(0, 0, 0, 0.025);
}
.nav-item.active {
  color: #1890ff;
}
.nav-icon {
  margin-right: 6px;
  font-style: normal;
}
.badge {
  margin-left: 6px;
  padding: 2px 6px;
  font-size: 12px;
  line-height: 1;
  border-radius: 10px;
  background: #ff4d4f;
  color: #fff;
  white-space: nowrap;
}
.has-child {
  position: relative;
}
.arrow {
  margin-left: 4px;
  width: 0;
  height: 0;
  border-left: 4px solid transparent;
  border-right: 4px solid transparent;
  border-top: 5px solid currentColor;
  transition: transform 0.3s;
}
.arrow.open {
  transform: rotate(180deg);
}
.sub-menu {
  position: absolute;
  top: 64px;
  left: 0;
  min-width: 160px;
  background: #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  overflow: hidden;
  z-index: 1001;
}
.sub-item {
  display: flex;
  align-items: center;
  padding: 0 16px;
  height: 40px;
  line-height: 40px;
  cursor: pointer;
  transition: background 0.3s;
}
.sub-item:hover {
  background: rgba(0, 0, 0, 0.025);
}
.nav-tools {
  display: flex;
  align-items: center;
  gap: 16px;
}
.search-box {
  display: flex;
  align-items: center;
}
.search-box input {
  width: 0;
  opacity: 0;
  transition: all 0.3s;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  padding: 4px 8px;
  height: 32px;
}
.search-box.active input {
  width: 200px;
  opacity: 1;
  margin-right: 8px;
}
.icon-search {
  cursor: pointer;
  font-style: normal;
}
.user-box {
  position: relative;
}
.user-trigger {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 0 8px;
}
.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-right: 8px;
}
.avatar-placeholder {
  font-style: normal;
  margin-right: 6px;
}
.username {
  margin-right: 4px;
  white-space: nowrap;
}
.user-dropdown {
  position: absolute;
  top: 56px;
  right: 0;
  min-width: 140px;
  background: #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  overflow: hidden;
  z-index: 1001;
}
.user-item {
  display: flex;
  align-items: center;
  padding: 0 16px;
  height: 36px;
  line-height: 36px;
  cursor: pointer;
  transition: background 0.3s;
}
.user-item:hover {
  background: rgba(0, 0, 0, 0.025);
}
.mobile-toggle {
  display: none;
  flex-direction: column;
  justify-content: center;
  width: 24px;
  height: 24px;
  cursor: pointer;
}
.bar {
  width: 18px;
  height: 2px;
  background: currentColor;
  margin: 2px 0;
  transition: 0.3s;
}
.mobile-drawer {
  position: fixed;
  top: 0;
  right: 0;
  width: 280px;
  height: 100vh;
  background: #fff;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
  z-index: 1002;
  display: flex;
  flex-direction: column;
}
.mobile-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  height: 64px;
  border-bottom: 1px solid #f0f0f0;
}
.mobile-title {
  font-size: 16px;
  font-weight: 500;
}
.icon-close {
  font-style: normal;
  cursor: pointer;
  font-size: 18px;
}
.drawer-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.45);
  z-index: 1001;
}
@media (max-width: 1200px) {
  .nav-item {
    padding: 0 10px;
  }

  .nav-icon {
    margin-right: 4px;
  }
}

@media (max-width: 992px) {
  .nav-item {
    padding: 0 8px;
    font-size: 13px;
  }

  .nav-icon {
    margin-right: 3px;
    font-size: 12px;
  }
}

@media (max-width: 768px) {
  .nav-menu.desktop {
    display: none;
  }
  .mobile-toggle {
    display: flex;
  }
  .username {
    display: none;
  }
  .search-box.active input {
    width: 140px;
  }
}
</style>
